<?php
namespace Components\User\Sha\Mutually\Sell;

class Logic {
  public function updateStatus($id, $status, $data) {
    $currentTime = time();

    switch($status) {
      case '90':
        $model = $this -> findFirstById($id);

        $model['user_mutually_buy_average'] -> status = $status;
        $model['user_mutually_buy_average'] -> finish_time = $currentTime;

        $model['user_mutually_sell_average'] -> status = $status;
        $model['user_mutually_sell_average'] -> finish_time = $currentTime;

        $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

        try {
          if(
            $model['user_mutually_buy'] -> loop_number % 2 == 0 ||
            $model['user_mutually_buy_average'] -> average_index >= 5
          ) {
            $model['user_mutually_buy'] -> status = $status;
            $model['user_mutually_buy'] -> finish_time = $currentTime;

            $model['user_mutually_buy'] -> setTransaction($transaction);
            if(!$model['user_mutually_buy'] -> update()) {
              $msgs = $model['user_mutually_buy'] -> getMessages();
              $transaction -> rollback($msgs[0] -> getMessage());
            }
          }

          $lastMutuallyBuyAverage = \Components\User\Sha\Mutually\Buy\AverageModel::findFirst([
            'conditions' => 'status = 90 AND is_receive = 0 AND user_id = ' . $model['buy_user'] -> id,
            'order' => 'id DESC'
          ]);
          if($lastMutuallyBuyAverage) {
            $amount = $lastMutuallyBuyAverage -> amount;
            if($model['user_mutually_buy_average'] -> average_index >= 4) {
              $amount = $lastMutuallyBuyAverage -> amount * 2;
            }
            if($model['user_mutually_buy'] -> loop_number % 2 == 0) {
              $lastMutuallyBuy = $lastMutuallyBuyAverage -> getUserMutuallyBuy();
              $amount = $lastMutuallyBuy -> amount + ($lastMutuallyBuy -> amount / $lastMutuallyBuy -> average);
            }
            $res = (new \Components\User\Sha\Wallet\Service()) -> updateIncAmount(
              $model['user_mutually_sell'] -> field,
              $lastMutuallyBuyAverage -> user_id,
              $amount,
              13109,
              null,null,null,null,null,null,
              '匹配完成',
              $transaction
            );

            if($res['code'] != 0) { $transaction -> rollback($res['msg']); }

            $lastMutuallyBuyAverage -> is_receive = 1;
            $lastMutuallyBuyAverage -> setTransaction($transaction);
            if(!$lastMutuallyBuyAverage -> update()) {
              $msgs = $lastMutuallyBuyAverage -> getMessages();
              $transaction -> rollback($msgs[0] -> getMessage());
            }
          }

          $model['user_mutually_buy_average'] -> setTransaction($transaction);
          if(!$model['user_mutually_buy_average'] -> update()) {
            $msgs = $model['user_mutually_buy_average'] -> getMessages();
            $transaction -> rollback($msgs[0] -> getMessage());
          }

          $model['user_mutually_sell_average'] -> setTransaction($transaction);
          if(!$model['user_mutually_sell_average'] -> update()) {
            $msgs = $model['user_mutually_sell_average'] -> getMessages();
            $transaction -> rollback($msgs[0] -> getMessage());
          }

          $transaction -> commit();
        } catch(\Exception $e) {
          return ['code' => -1, 'msg' => $e -> getMessage()];
        }

        return ['code' => 0, 'msg' => '确认成功'];
      default:
        return ['code'=>-1,'msg'=>'此状态未定义'];
    }
  }

  public function findFirstById($id) {
    $builder = $this -> makeBuilder()
      -> addFrom(AverageModel::class, 'user_mutually_sell_average')
      -> andWhere('user_mutually_sell_average.id = '.$id)
      -> andWhere('user_mutually_sell_average.user_mutually_sell_id = user_mutually_sell.id')

      -> addFrom('Components\\User\\Sha\\Model', 'buy_user')
      -> andWhere('buy_user.id = user_mutually_sell_average.buy_user_id')

      -> addFrom('Components\\User\\Sha\\Mutually\\Buy\\AverageModel', 'user_mutually_buy_average')
      -> andWhere('user_mutually_sell_average.user_mutually_buy_average_id = user_mutually_buy_average.id')

      -> addFrom('Components\\User\\Sha\\Mutually\\Buy\\Model', 'user_mutually_buy')
      -> andWhere('user_mutually_buy_average.user_mutually_buy_id = user_mutually_buy.id')

      -> orderBy('user_mutually_sell_average.status ASC, user_mutually_sell_average.id ASC');

    return array_merge(['code'=>0], $builder -> getQuery() -> getSingleResult() -> toArray());
  }

  protected function getPaginate($builder, $limit, $page) {
    return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
      'builder' => $builder,
      'limit' => $limit,
      'page' => $page
    ])) -> getPaginate()];
  }

  public function makeBuilder() {
    return (new \Phalcon\Mvc\Model\Query\Builder())
      -> from([
        'user' => 'Components\\User\\Sha\\Model',
        'user_mutually_sell' => __NAMESPACE__ . '\\Model'
      ])
      -> where('user.id = user_mutually_sell.user_id');
  }

  public function pagerUseParameters($limit, $page, $parameters = []) {
    $builder = $this -> makeBuilder()
      -> addFrom(AverageModel::class, 'user_mutually_sell_average')
      -> andWhere('user_mutually_sell_average.user_mutually_sell_id = user_mutually_sell.id')

      -> addFrom('Components\\User\\Sha\\Model', 'buy_user')
      -> andWhere('buy_user.id = user_mutually_sell_average.buy_user_id')

      -> addFrom('Components\\User\\Sha\\Mutually\\Buy\\AverageModel', 'user_mutually_buy_average')
      -> andWhere('user_mutually_sell_average.user_mutually_buy_average_id = user_mutually_buy_average.id')

      -> orderBy('user_mutually_sell_average.status ASC, user_mutually_sell_average.id ASC');

    if(!empty($parameters)) {
      if(isset($parameters['conditions'])) {
        foreach($parameters['conditions'] as $k => $v) {
          foreach($v as $kk => $vv) {
            $builder -> andWhere($k.'.'.$kk.' = '.$vv);
          }
        }
      }
    }

    return $this -> getPaginate($builder, $limit, $page);
  }

  public function pager($limit, $page) {
    $builder = $this -> makeBuilder()
      -> orderBy('user_mutually_sell.id ASC');

    return $this -> getPaginate($builder, $limit, $page);
  }
}
